<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #box {
            width: 300px;
            height: 300px;
            background: #ccc;
            position: absolute;
        }
    </style>
</head>

<body>
    <div id="box"></div>
</body>
<script>
    // 获取元素
    var obox = document.getElementById("box");

    drag(obox);

    function drag(node) {
        node.onmousedown = function (eve) {
            // console.log(1)
            var e = eve || window.event;
            // 记录鼠标和被拖拽物体的相对位置
            var offsetX = e.clientX - node.offsetLeft;
            var offsetY = e.clientY - node.offsetTop;
            // 被拖拽物体保持相对距离跟鼠标移动
            document.onmousemove = function (eve) {
                var e = eve || window.event;
                var l = e.clientX - offsetX;
                var t = e.clientY - offsetY;
                // 限制左右出界
                if (l <= 0) l = 0;
                // 获取当前浏览器的窗口宽度
                var windowWidth = document.documentElement.clientWidth || document.body.clientWidth;
                if (l >= windowWidth - node.offsetWidth) {
                    l = windowWidth - node.offsetWidth
                }
                // 限制上下出街
                if (t <= 0) t = 0;
                // 获取当前浏览器窗口的高
                var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
                if (t >= windowHeight - node.offsetHeight) {
                    t = windowHeight - node.offsetHeight
                }
                node.style.left = l + 'px';
                node.style.top = t + 'px';
            }
        }
        // 鼠标抬起
        document.onmouseup = function () {
            // 取消拖拽
            document.onmousemove = null;
        }
    }
</script>

</html>